package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.PurchaseOrder;
import com.example.electricbicycle.service.WarehouseServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/OrderReviewServlet")
public class OrderReviewServlet extends HttpServlet {
    private WarehouseServiceImpl warehouseServiceImpl = new WarehouseServiceImpl();

    // 处理GET请求（分页查询）
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int page = 1;
        int pageSize = 5;
        try {
            page = Integer.parseInt(req.getParameter("page"));
        } catch (NumberFormatException e) {
            // 默认第一页
        }

        // 获取分页数据
        List<PurchaseOrder> orderList = warehouseServiceImpl.getPendingOrders(page, pageSize);
        int totalOrders = warehouseServiceImpl.getTotalPendingOrders();
        int totalPages = (int) Math.ceil((double) totalOrders / pageSize);

        // 设置请求属性（保持分页状态）
        req.setAttribute("orderList", orderList);
        req.setAttribute("totalPages", totalPages);
        req.setAttribute("currentPage", page);

        // 转发到JSP页面
        req.getRequestDispatcher("/warehouse/orderReview.jsp").forward(req, resp);
    }

    // 处理POST请求（审核通过）
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int orderId = Integer.parseInt(req.getParameter("orderId"));
        boolean success = warehouseServiceImpl.approveAndStockIn(orderId);

        // 设置审核结果提示
        req.setAttribute("approveSuccess", success);

        // 保持当前分页状态（从请求参数中获取）
        String currentPageStr = req.getParameter("page");
        int currentPage = (currentPageStr != null) ? Integer.parseInt(currentPageStr) : 1;

        // 重新查询当前页数据（审核后可能需要刷新列表）
        List<PurchaseOrder> orderList = warehouseServiceImpl.getPendingOrders(currentPage, 5);
        req.setAttribute("orderList", orderList);

        // 转发到JSP页面
        req.getRequestDispatcher("/warehouse/orderReview.jsp").forward(req, resp);
    }
}